package com.tg.paw.ums.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tg.paw.common.util.CommonResult;
import com.tg.paw.ums.entity.Role;
import com.tg.paw.ums.entity.RolePermissionRelation;
import com.tg.paw.ums.params.PermissionButtonsParams;
import com.tg.paw.ums.enmus.PermissionButtonEnum;
import com.tg.paw.ums.entity.Permission;
import com.tg.paw.ums.params.RolePermissionParams;
import com.tg.paw.ums.service.IApiPermissionService;
import com.tg.paw.ums.service.IPermissionService;
import com.tg.paw.ums.service.IRolePermissionRelationService;
import com.tg.paw.ums.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Rubble
 * @date 2020/10/24
 */
@Service
public class ApiPermissionServiceImpl implements IApiPermissionService {
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRolePermissionRelationService rolePermissionRelationService;

    @Override
    public CommonResult updatePermissionButtons(PermissionButtonsParams params) {

        List<Permission> permissionList = permissionService.getPermissionByParentId(params.getParentId());
        List<String> permissionButtons = params.getButtonPermissions();
        // 删除  枚举列表中存在  新权限按钮没有且数据库存在则删除
        for (PermissionButtonEnum itemEnum : PermissionButtonEnum.values()) {
            List<Permission> enumDBList = permissionList.stream()
                    .filter(item->itemEnum.getLabel().equals(item.getPermissionName()))
                    .collect(Collectors.toList());
            if(!permissionButtons.contains(itemEnum.getValue())  && !enumDBList.isEmpty()){
                permissionService.removeById(enumDBList.get(0).getPermissionId());
            }
        }
        Permission parentPermission = permissionService.getById(params.getParentId());
        // 新增
        for (String permissionValue : permissionButtons) {
            PermissionButtonEnum permissionButtonEnum = PermissionButtonEnum.getByValue(permissionValue);
            if(permissionButtonEnum==null){
                return CommonResult.failed("not support permissionValue: " + permissionValue);
            }
            boolean isNotExist = permissionList.stream()
                    .filter(item->permissionButtonEnum.getLabel().equals(item.getPermissionName()))
                    .collect(Collectors.toList()).isEmpty();
            if(isNotExist){
                Permission entity = new Permission();
                entity.setParentId(params.getParentId());
                entity.setPermissionName(permissionButtonEnum.getLabel());
                entity.setAuthority(parentPermission.getAuthority()+":"+permissionButtonEnum.getValue());
                entity.setPermissionType(2);
                entity.setCreateTime(new Date());
                permissionService.save(entity);
            }
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult updateRolePermission(RolePermissionParams params) {
        Role role = roleService.getById(params.getRoleId());
        if(role==null){
            return CommonResult.failed("Unknown roleId: "+ params.getRoleId());
        }
        final String ADMIN ="admin";
        if(ADMIN.equals(role.getRoleName())){
            return CommonResult.failed("admin不能更改");
        }
        List<Long> permissionIds = params.getPermissionIds();
        Set<Long> immediateIds = new HashSet<>();
        // 处理checkbox的 immediate 选项
        if(CollUtil.isNotEmpty(permissionIds)){
            List<Permission> allPermissions = permissionService.list();
            Map<Long,Long> map = new HashMap<>(16);
            CollUtil.toMap(allPermissions,map,Permission::getPermissionId,Permission::getParentId);
            for (Long permissionId : permissionIds) {
                buildImmediatePermissions(permissionId,map,permissionIds,immediateIds);
            }
        }

        // 删除角色已有权限
        LambdaQueryWrapper<RolePermissionRelation> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(RolePermissionRelation::getRoleId,params.getRoleId());
        rolePermissionRelationService.remove(queryWrapper);

        // 新增权限
        List<RolePermissionRelation> entityList = new ArrayList<>();
        for (Long permissionId : permissionIds) {
            RolePermissionRelation entity = new RolePermissionRelation();
            entity.setRoleId(params.getRoleId());
            entity.setPermissionId(permissionId);
            entityList.add(entity);
        }
        for (Long immediateId : immediateIds) {
            RolePermissionRelation entity = new RolePermissionRelation();
            entity.setRoleId(params.getRoleId());
            entity.setPermissionId(immediateId);
            entity.setImmediate(1);
            entityList.add(entity);
        }
        if(!entityList.isEmpty()){
            rolePermissionRelationService.saveBatch(entityList);
        }

        return CommonResult.success();
    }

    /**
     * 查询父路径半选状态
     * @param id 检查节点
     * @param map 全部权限 value 为 ParentId
     * @param checkedIds 已选择的ids
     * @param immediateIds 半选ids
     */
    private void buildImmediatePermissions(Long id, Map<Long,Long> map,List<Long> checkedIds,Set<Long> immediateIds){
        if(id.longValue()==0){
            return;
        }
        if(!checkedIds.contains(id)){
            immediateIds.add(id);
        }
        if(map.containsKey(id)){
            Long parentId = map.get(id);
            buildImmediatePermissions(parentId,map,checkedIds,immediateIds);
        }
    }
}
